package com.jysz.certificate.service.pm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.jysz.certificate.constant.ConfigTypeConstants.ConfigTypes;
import com.jysz.certificate.constant.ConfigTypeConstants.PerformanceConfig;
import com.jysz.certificate.persistence.dao.pm.PmUserDao;
import com.jysz.certificate.persistence.dao.system.OrganizationDao;
import com.jysz.certificate.persistence.dao.system.UserDao;
import com.jysz.certificate.persistence.enums.PostType;
import com.jysz.certificate.persistence.enums.mytask.Prwarningtype;
import com.jysz.certificate.persistence.enums.pm.PmUserStype;
import com.jysz.certificate.persistence.model.mytask.Prewarning;
import com.jysz.certificate.persistence.model.pm.PerformanceAssign;
import com.jysz.certificate.persistence.model.pm.PmUser;
import com.jysz.certificate.persistence.model.pm.PmUserList;
import com.jysz.certificate.persistence.model.system.Organization;
import com.jysz.certificate.persistence.model.system.Shop;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.service.system.OrganizationService;
import com.jysz.certificate.service.system.ShopService;
import com.jysz.certificate.service.system.UserService;
import com.jysz.certificate.utils.CertificateUtils;
import com.jysz.certificate.utils.DateUtil;
import com.jysz.webcore.ssh.orm.hibernate.ThreadLocalHolder;
import com.jysz.webcore.ssh.orm.hibernate.support.Page;
import com.jysz.webcore.ssh.service.EntityService;

@Service
public class PmUserService  extends EntityService<PmUser ,Long,PmUserDao>{

	@Resource
	public PmUserDao pmUserDao;
	
	@Resource
	public UserDao userDao;
	
	@Resource
	public OrganizationDao organizationDao;
	
	@Resource
	private OrganizationService organizationService;
	
	@Resource
	private UserService userService;
	
	@Resource
	private ShopService shopService;
	@Resource
	private PmUserListService pmUserListService;
	
	@Override
	public PmUserDao getEntityDao() {
		return pmUserDao;
	}
	
	/**
	 * 添加是 获得人员
	 * @param user
	 * @return
	 */
	public Page<User> addUserPage(User user,Long[] ObjId, int pageNo, int pageSize,String masht){
		PmUser pmUser =new PmUser();
		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
		pmUser.setAuthor(user);
		System.out.println("masht"+masht);
		if(masht.equals("1")){
			pmUser.setState(PmUserStype.NOTSTART);
		}else{
			pmUser.setState(PmUserStype.SUBMITED);
			pmUser.setDeliveryTime(new Date());
			pmUser.setDeliceryMM(dft.format(new Date()));
		}
		
		String name="";
		List<PmUserList> pmUserLists = new ArrayList<PmUserList>();
		Page<User> pageUser=null;
		Page<Organization> orPage = null;//查询所有的店
		if(user.getPost().equals(PostType.Admin)){//管理员
			orPage = organizationService.findPageUser(1, 10000);
		}else{
			orPage = organizationService.findPageUser(ObjId, 1, 10000);
		}
		if(null != orPage){
			Set<Long> set = new HashSet<Long>();
			List<Organization> organizations = orPage.getResult();
			if(organizations.size()>0){
				for(int i=0;i<organizations.size();i++){
					List<User> users = new ArrayList<User>();
					PmUserList pmUserList = new PmUserList();
					Organization organization = organizations.get(i);
					if(set.add(organization.getParent().getId())){//判断是否重复区域
						name += organization.getParent().getName()+",";
					}
					Shop shop = shopService.find(organization.getObjectId());
					List<Organization> oList = organizationService.findUserShopByShopId(shop.getId());
					for(int j=0;j<oList.size();j++){
						Organization org = oList.get(j);
						User us = userService.find(org.getObjectId());
						users.add(us);
					}
					pmUserList.setOrganization(organization.getParent());
					pmUserList.setPmUser(pmUser);
					pmUserList.setUsers(users);
					pmUserList.setShop(shop);
					pmUserLists.add(pmUserList);
				}
			}
			pmUser.setUsers(pmUserLists);
			name = name.substring(0,name.length()-1);
			pmUser.setArea(name);
			pmUser.setMark(true);
			this.save(pmUser);
		}
		
		return pageUser;
	}
	public Page<PmUser> findPage(PmUser pmUser, int pageNumber,int pageSize){
		Criteria criteria = pmUserDao.createCriteria();
		criteria.addOrder(Order.desc("id"));
		String userName = ThreadLocalHolder.get().toString();
		User user = userDao.getUserByName(userName);
		if(user.getPost().equals(PostType.Manager)){
			List<Organization> orgList = organizationDao.getAreaByUserManagerId(user.getId());
			Disjunction dis=Restrictions.disjunction();   
			for (Organization area : orgList) {
				dis.add(Restrictions.like("area", area.getName(),MatchMode.ANYWHERE));
			}
			criteria.add(dis);
		}
		
		if(pmUser != null){
			if(null != pmUser.getAuthor()){
				if(StringUtils.isNotBlank(pmUser.getAuthor().getRealName()))
					criteria.createCriteria("author").add(Restrictions.like("realName",  pmUser.getAuthor().getRealName(), MatchMode.ANYWHERE));
			}
			if(pmUser.getState() != null){
				criteria.add(Restrictions.eq("state", pmUser.getState()));
			}
			if(pmUser.getDeliveryTime() != null){
				criteria.add(Restrictions.between("deliveryTime",DateUtil.getFirstdayLastdayMonthOne(pmUser.getDeliveryTime()), DateUtil.getFirstdayLastdayMonth(pmUser.getDeliveryTime())));
			}
		}
		return this.findPage(criteria, pageNumber, pageSize);
		
	}
	public List<Prewarning> remindPmUser(User user){
		
		Page<Organization> orPage = organizationService.findPageUser(user.getId(), 1, 10000);
		
		Integer nextDay = CertificateUtils.getIntegerPropertyByKeys(ConfigTypes.PERFORMANCE_CONFIG.getKey(), 
				PerformanceConfig.USER_LIST_REMINE_DAY_QTY.getField());//获得绩效人员名单的提醒日期
		
		List<Prewarning> prewarnings = new ArrayList<Prewarning>();
		String name=null;
		if(null != orPage){
			Set<String> set = new HashSet<String>();
			List<Organization> organizations = orPage.getResult();
			if(organizations.size()>0){
				name = "";
				for(int i=0;i<organizations.size();i++){
					Organization organization = organizations.get(i);
					if(set.add(organization.getParent().getName())){//判断是否重复区域
						name += organization.getParent().getName()+",";
					}
				}
			}
		}
		
		if(name != null){
			name= name.substring(0,name.length()-1);
			String values[] = name.split(",");
			for(int i=0;i<values.length ;i++){
				Criteria criteria = pmUserDao.createCriteria();
				criteria.add(Restrictions.like("area", values[i], MatchMode.ANYWHERE));
				criteria.add(Restrictions.eq("state", PmUserStype.SUBMITED));
				criteria.add(Restrictions.ge("deliveryTime", DateUtil.getFirstdayLastdayMonthOne(new Date())));
				criteria.add(Restrictions.le("deliveryTime", DateUtil.getFirstdayLastdayMonth(new Date())));
				List<PmUser> pmUsers = criteria.list();
				
				if(pmUsers.size()==0){
					Prewarning prewarning = new Prewarning();
					prewarning.setBool(true);
					prewarning.setPrwarningtype(Prwarningtype.TREATY);
					prewarning.setMsg("您有："+values[i]+"  区域的绩效人员名单没有发布");
					prewarning.setUrlAddress("/pm/user/index.do");
					prewarnings.add(prewarning);
				}
			}
		}
		return prewarnings;
	}
	/**
	 * 判断用户是否发布人员名单
	 * @param userId 用户ID
	 * @param date 需要判断的月份
	 * @return 存在 true 没有 false
	 */
	public Boolean ifYouBe(Long userId,Date date,String area){
		Criteria criteria = pmUserDao.createCriteria();
		criteria.add(Restrictions.ge("deliveryTime", DateUtil.getFirstdayLastdayMonthOne(date)));
		criteria.add(Restrictions.le("deliveryTime", DateUtil.getFirstdayLastdayMonth(date)));
		criteria.add(Restrictions.like("area", area,MatchMode.ANYWHERE));
		criteria.add(Restrictions.eq("state", PmUserStype.SUBMITED));
//		criteria.add(Restrictions.eq("author.id", userId));
		List<PmUser> pmUsers = criteria.list();
		if(pmUsers.size()>0){
			return true;
		}
		return false;
	}

//	public List<PmUser> findAllByMonth(String monthDate) {
//		return pmUserDao.findAllByMonth(monthDate);
//	}
	
	

	/**
	 * 根据区域生成人员名单。
	 * @param area
	 * @param monthDate 
	 * @param entity 
	 */
	public PmUser saveGeneratorPmUser(Organization area, String monthDate, PerformanceAssign performanceAssign) {
		List<Organization> shops = area.getShopChilds();
		if(shops == null || shops.size() < 1 ){
			return null;
		}
		PmUser pmUser = new PmUser();
		pmUser.setAuthor(null);
		pmUser.setArea(area.getName());
		pmUser.setDeliceryMM(monthDate);
		pmUser.setDeliveryTime(DateUtil.getDate(monthDate, "yyyy-MM"));
		pmUser.setMark(false);
		pmUser.setState(PmUserStype.SUBMITED);
		
		List<PmUserList> pmUserLists = new ArrayList<PmUserList>();
		for (Iterator<Organization> iterator = shops.iterator(); iterator.hasNext();) {
			Organization organization = iterator.next();
			
			List<User> users = new ArrayList<User>();
			PmUserList pmUserList = new PmUserList();
	
			Shop shop = shopService.find(organization.getObjectId());
			List<Organization> oList = organizationService.findUserShopByShopId(shop.getId());
			for( int j = 0; j < oList.size(); j++ ){
				Organization org = oList.get( j );
				User us = userService.find( org.getObjectId() );
				users.add(us);
			}
			pmUserList.setOrganization( organization.getParent() );
			pmUserList.setPmUser( pmUser );
			pmUserList.setUsers( users );
			pmUserList.setShop( shop );
			pmUserLists.add( pmUserList );
		}
		
		pmUser.setUsers( pmUserLists );
		
		pmUser.setPerformanceAssign(performanceAssign);
		this.save(pmUser);
		
		return pmUser;
	}

	/**
	 * 根据绩效删除该绩效月份自动生成的人员名单。
	 * @param pa
	 */
	@SuppressWarnings("unchecked")
	public void deleteByPerformanceAssign(PerformanceAssign pa) {
		String monthDate = pa.getMonthDate();
		
		Criteria criteria = pmUserDao.createCriteria();
		criteria.add(Restrictions.eq("deliceryMM", monthDate));
		criteria.add(Restrictions.eq("mark", false));
		List<PmUser> pmUsers = criteria.list();
		
		if(pmUsers != null && pmUsers.size() > 0){
			pmUserDao.destoryAll(pmUsers);
		}

	}
	
}
